import os
import sys
from datetime import datetime

import bencode

from logger import Logger
from util import rename_file

base_path = "E:/torrents"
sys.stdout = Logger(datetime.now().strftime("log/%Y%m%d_%H%M%S") + ".txt")

def get_torrent_name(torrent_file_path):
    # 读取.torrent文件
    with open(torrent_file_path, 'rb') as file:
        torrent_data = file.read()

    # 解码Bencode数据
    decoded_data = bencode.bdecode(torrent_data)
    single_file_name = decoded_data['info']['name']
    return single_file_name

def get_torrent_files(torrent_file_path):
    # 读取.torrent文件
    with open(torrent_file_path, 'rb') as file:
        torrent_data = file.read()

    # 解码Bencode数据
    decoded_data = bencode.bdecode(torrent_data)

    # 获取文件列表
    files = decoded_data['info']['files']
    if files:
        # files是一个列表，其中包含字典，每个字典代表一个文件
        file_names = []
        for file_info in files:
            # 每个文件信息是一个字典，其中'length'是文件大小，'path'是文件路径
            file_path = file_info['path']
            # 将路径列表中的每个元素解码成字符串，并用'/'连接起来
            file_name = '/'.join(file_path)
            file_names.append(file_name)
        return file_names
    else:
        # 如果没有文件列表，只有一个文件
        single_file_name = decoded_data['info']['name']
        return [single_file_name]


for root, dirs, files in os.walk(base_path):
    for file in files:
        try:
            # 检查文件扩展名是否为.json
            if file.endswith('.torrent'):
                print(f'processing {file}')
                # 构造完整的文件路径
                file_path = os.path.join(root, file)
                torrent_name = get_torrent_name(file_path)
                rename_file(file_path, torrent_name)
                print(f'renamed to {torrent_name}')
        except Exception as ex:
            print(f"error: {ex}")

# 使用函数
# torrent_file_path = 'F4DB14B68D66F48307B9FCD21A7392A6E42CDF06.torrent'
# torrent_name = get_torrent_name(torrent_file_path)
# print(f'{torrent_name}')
# rename_file(torrent_file_path, torrent_name)
# file_names = get_torrent_files(torrent_file_path)
# for name in file_names:
#     print(name)